﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(HairIns))]
[CanEditMultipleObjects]
public class HairInsEditor : E_ShowButtons<HairIns> { }
#endif
public class HairIns : MonoBehaviour
{
    public Transform[] pts;
    public bool updateCollider;
    Key3 k1, k2, k3;
    Hair hair { get { return GetComponent<Hair>(); } }
    [ShowButton]
    void GetCurveFromUI()
    {
        hair.genData.curveCrsSecFront = FindObjectOfType<UICurve>().curveMirror.Clone();
    }
    [ShowButton]
    void UseDefaultCurves()
    {
        hair.genData.UseDefaultCurves();
    }
    void Start()
    {
        CreateCurve();
    }
    [ShowButton]
    void AddHair()
    {
        var go = gameObject;
        var rig = new GameObject("Rig").transform;
        rig.SetParent(go);

        GenMeshTool.GenHair(hair, FindObjectOfType<HairGen>().hairMat, rig);

        Curve3Edit.I.curve = hair.curveData.curve;
    }    
    [ShowButton]
    private void Apply()
    {
        var smr = gameObject.GetComponent<SkinnedMeshRenderer>();
        if (smr != null)
        {
            smr.sharedMesh.RecalculateBounds();
            smr.sharedMesh.RecalculateNormals();
            smr.sharedMesh.RecalculateTangents();
        }
        transform.ClearChildren();
        AddHair();
    }    
    void CreateCurve()
    {
        var c = hair.curveData;
        k1 = new Key3();
        k2 = new Key3();
        c.curve = new Curve3();
        c.curve.Add(k1);
        c.curve.Add(k2);

        k1.inMode = KeyMode.None;
        k1.vector = pts[0].position;
        k1.outTangent = pts[1].position;
        k2.inTangent = pts[2].position;
        k2.vector = pts[3].position;

        //append
        k3 = new Key3();
        c.curve.Add(k3);

        k2.outTangent = pts[4].position;
        k3.inTangent = pts[5].position;
        k3.vector = pts[6].position;
        k3.outMode = KeyMode.None;

        c.SnapBonesToCurve();

        foreach (var pt in pts)
        {
            pt.gameObject.SetActive(false);
        }
    }
    void Update()
    {
        if (updateCollider)
        {
            this.UpdateMeshCol();
        }
        var c = hair.curveData;
        if (c.bones != null && c.bones.Length > 0)
        {
            c.SnapBonesToCurve();
        }
    }
}
